package com.pn.service.impl;

import com.pn.entity.Result;
import com.pn.mapper.ProductTypeMapper;
import com.pn.model.ProductType;
import com.pn.service.ProductTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = "com.pn.service.impl.ProductTypeServiceImpl")
@Service
public class ProductTypeServiceImpl implements ProductTypeService {

    @Autowired
    private ProductTypeMapper productTypeMapper;



    /**
     * 查询商品目录树
     *
     * @return
     */
    @Cacheable("'all:typeTree'")
    @Override
    public List<ProductType> productTypeTree() {
        //查出所有商品分类
        List<ProductType> allProductTypeList = productTypeMapper.findAllProductType();
        //将所有商品分类转成商品分类树
        List<ProductType> typeTreeList = allTypeToTypeTree(allProductTypeList, 0);

        return typeTreeList;
    }


    //将所有商品分类转换为商品分类树的递归算法
    private List<ProductType> allTypeToTypeTree(List<ProductType> typeList, Integer pid) {
        //拿到所有一级分类
        List<ProductType> firstLevelType = new ArrayList<>();
        for (ProductType productType : typeList) {
            if (productType.getParentId().equals(pid)) {
                firstLevelType.add(productType);
            }
        }

        //查出每一个一级分类下面的所有二级分类
        for (ProductType productType : firstLevelType) {
            List<ProductType> secondLevelType = allTypeToTypeTree(typeList, productType.getTypeId());
            productType.setChildProductCategory(secondLevelType);
        }
        return firstLevelType;

    }


    /**
     * 校验分类编码是否已经存在
     * @param typeCode
     * @return
     */
    @Override
    public Result checkTypeCode(String typeCode) {

        //根据分类编码查询分类，并判断是否存在
        ProductType productType = new ProductType();
        productType.setTypeCode(typeCode);
        ProductType prodType = productTypeMapper.findTypeByCodeOrName(productType);
        //返回值
        return Result.ok(prodType==null);
    }


}
